<template>
  <ex-dialog width="50%" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <div class="main" v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-form-item label="视频标题：" prop="title" :label-width="labelWidth">
          <el-input v-model="ruleForm.title" placeholder="请输入" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="视频副标题：" prop="secondTitle" :label-width="labelWidth">
          <el-input v-model="ruleForm.secondTitle" placeholder="请输入" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="排序：" prop="sort" :label-width="labelWidth">
          <el-input v-model="ruleForm.sort" placeholder="请输入" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="文章状态：" prop="status" :label-width="labelWidth">
          <el-radio-group v-model="ruleForm.status">
            <el-radio label="1">显示</el-radio>
            <el-radio label="2">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="视频封面：" :label-width="labelWidth">
          <el-upload class="avatar-uploader2" :action="uploadUrl" :before-upload="beforeUploadImg" :show-file-list="false" :on-success="imgSuccess" v-loading="imgLoading"
            :on-error="onError" :on-progress="onProgress" :multiple="false">
            <img class="banner_img" :src="ruleForm.imgUrl" alt="" v-if="ruleForm.imgUrl">
            <i class="el-icon-plus" style="font-size: 28px" v-else></i>
          </el-upload>
          <p class="tips_txt">建议上传尺寸：760*500</p>
        </el-form-item>
        <el-form-item label="视频上传" prop="videoUrl" :label-width="labelWidth">
          <!-- action必选参数, 上传的地址 -->
          <el-upload class="avatar-uploader2 el-upload--text" :action="videoUploadUrl" :show-file-list="false"
            :on-success="handleVideoSuccess" :before-upload="beforeUploadVideo" :on-progress="uploadVideoProcess">
            <video v-if="ruleForm.videoUrl !='' && videoFlag == false" :src="ruleForm.videoUrl"
              class="avatar-uploader2" controls="controls">您的浏览器不支持视频播放</video>
            <i v-else-if="ruleForm.videoUrl =='' && videoFlag == false" class="el-icon-plus avatar-uploader-icon"></i>
            <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent"></el-progress>
          </el-upload>
          <p class="text">请保证视频格式正确，且不超过500M</p>
        </el-form-item>
      </el-form>
    </div>
    <div class="button_box">
      <el-button type="primary" :loading="AgreeDisable" @click="submitForm('ruleForm')" v-if="id==null">立即创建</el-button>
      <el-button type="primary" :loading="AgreeDisable" @click="editForm('ruleForm')" v-if="id!=null">保存</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ex-dialog>
</template>
<script>
  // components
  import Loading from "@/components/Loading/index";
  // api
  import {
    addVideo,
    editVideo,
    videoDetail,
  } from "@/api/officialWebsite";

  export default {
    components: {
      Loading,
    },
    props: {
      visible: Boolean,
      id: String,
    },
    data() {
      return {
        title: '新增视频',
        loading: false,
        videoFlag: false,
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile",
        videoUploadUrl: process.env.VUE_APP_BASE_API + "/common/v1/upload",
        imgLoading: false,
        videoUploadPercent: 0,
        info: {},
        AgreeDisable: false,
        options: [],
        labelWidth: '150px',
        ruleForm: {
          title: "", //标题 
          secondTitle: "", //副标题
          sort: '', //排序
          status: '1', //视频状态（1显示 2隐藏）
          imgUrl: '', //视频封面url
          videoUrl: '', //视频url
        },
        rules: {
          title: [{
            required: true,
            message: '请输入标题',
            trigger: ['change', 'bulr'],
          }],
          secondTitle: [{
            required: true,
            message: '请输入副标题',
            trigger: ['change', 'bulr'],
          }],
          sort: [{
            required: true,
            message: "请输入排序",
            trigger: ['change', 'bulr'],
          }],
          status: [{
            required: true,
            message: '请选择视频状态',
            trigger: 'change'
          }],
          videoUrl: [{
            required: true,
            message: '请上传视频',
            trigger: ['change', 'bulr'],
          }],
        },
      };
    },
    computed: {},
    created() {
      console.log(this.id)
      if (this.id != null) {
        this.title = '编辑视频'
        this.getInfo()
      }
    },
    methods: {
      //取消
      handleClose(formName) {
        this.$emit("update:visible", false);
      },
      getInfo() { //获取信息详情
        this.loading = true
        videoDetail(this.id).then((res) => {
            let info = res.result
            this.ruleForm.title = info.title
            this.ruleForm.secondTitle = info.secondTitle
            this.ruleForm.sort = info.sort
            this.ruleForm.status = info.status
            this.ruleForm.imgUrl = info.imgUrl
            this.ruleForm.videoUrl = info.videoUrl
            this.loading = false
          })
          .finally(() => {
            this.loading = false;
          });
      },
      beforeUploadImg(file){
        if (['image/jpeg', 'image/png','image/jpg'].indexOf(file.type) == -1) {
          this.$message.error('请上传正确的图片格式');
          return false;
        }
      },
      beforeUploadVideo(file) {
        const isLt10M = file.size / 1024 / 1024 < 500;
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) == -1) {
          this.$message.error('请上传正确的视频格式');
          return false;
        }
        if (!isLt10M) {
          this.$message.error('上传视频大小不能超过500MB哦!');
          return false;
        }
      },
      uploadVideoProcess(event, file, fileList) {
        this.videoFlag = true;
        console.log('file', file.percentage.toFixed(0))
        let urlFile = file.percentage.toFixed(0)
        this.videoUploadPercent = Number(urlFile);
      },
      handleVideoSuccess(res, file) { //获取上传地址
        this.videoFlag = false;
        this.videoUploadPercent = 0;
        if (res.code == 200) {
          // this.videoForm.videoUploadId = res.data.uploadId;
          this.ruleForm.videoUrl = res.result.url;
        } else {
          this.$message.error('视频上传失败，请重新上传！');
        }
      },
      imgSuccess(res, file) { //图片上传成功时
        console.log(res.result.url)
        this.ruleForm.imgUrl = res.result.url
        this.imgLoading = false
      },
      onProgress(file) { //封面上传时
        this.imgLoading = true
        console.log(this.imgLoading)
      },
      onError(file) {
        this.imgLoading = false
      },
      submitForm(formName) {
        //创建确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   alert("submit!");editGroupon
            this.AgreeDisable = true
            var params = {
              ...this.ruleForm,
            };
            addVideo(params).then((res) => {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.AgreeDisable = false
                }, 1000);
              })
              .finally(() => {
                this.AgreeDisable = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      editForm(formName) {
        //编辑确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   alert("submit!");editGroupon
            this.AgreeDisable = true
            var params = {
              id: this.id,
              ...this.ruleForm,
            };
            editVideo(params).then((res) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.AgreeDisable = false
                }, 1000);
              })
              .finally(() => {
                this.AgreeDisable = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
  };

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

  .main {
    padding: 20px 20px;
  }

  .from_box {
    display: flex;
    margin-bottom: 20px;
  }

  .from_box_l {
    width: 110px;
    color: #606266;
    font-size: 14px;
    font-weight: bold;
  }

  .from_box_r {
    color: #333;
    font-size: 15px;
    flex: 1;
  }

  .el_table_box {
    padding: 0 20px 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .el_table_box_h {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #f3f3f3;
    margin-bottom: 14px;
  }

  .el_table_box_h_title {
    border-left: 4px solid #ff9300;
    padding-left: 4px;
  }

  .carousel_box {
    width: 400px;
    margin-bottom: 20px;
  }

  .swiper_img {
    width: 100%;
    height: 100%;
  }

  .carousel_box_two {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .phone_box {
    width: 100px;
    height: 100px;
    margin: 0 10px 10px 0;
  }

  .button_box {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
  }

  ::v-deep .avatar-uploader2 .el-upload {
    width: 100% !important;
  }

  .avatar-uploader2 {
    width: 228px;
    height: 128px;
    text-align: center;
    line-height: 128px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
  }

  .banner_img {
    width: 228px;
    height: 128px;
  }

</style>
